# encoding: utf-8
# author: 侯佳涛
# file_name: utils
# create_time: 2022/2/10, 下午6:01
"""
自定义用户登录
"""
import re
from django.contrib.auth.backends import ModelBackend
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from itsdangerous import BadData
from django.conf import settings

from .models import User
from . import constants


def check_email_verify_token(token):
    """对邮箱验证的token进行反序列化"""
    # 创建序列化对象
    s = Serializer(secret_key=settings.SECRET_KEY, expires_in=constants.VERIFY_EMAIL_TOKEN_EXPIRES)

    # 对token进行反序列化操作
    try:
        data = s.loads(token)
    except BadData:  # 反序列化失败
        return None
    else:
        # 获取信息
        user_id = data.get('user_id')
        email = data.get('email')
        # 查询用户
        try:
            user = User.objects.get(id=user_id, email=email)
        except User.DoesNotExist:
            return None
        else:
            return user


def generate_email_verify_url(user):
    """生成邮箱验证链接"""
    # 创建序列化对象
    s = Serializer(secret_key=settings.SECRET_KEY, expires_in=constants.VERIFY_EMAIL_TOKEN_EXPIRES)

    # 构建需要序列化的数据
    user_id = user.id
    email = user.email
    data = {'user_id': user_id, 'email': email}

    # 对数据序列化
    token = s.dumps(data).decode()

    # 返回拼接序列化查询字符串的链接
    return settings.EMAIL_VERIFY_URL + '?token=' + token


def get_user(account):
    """
    根据传入的account获取用户对象
    :param account: 用户名或者手机号
    :return:
    """
    # 根据account从User中查询用户对象
    try:
        if re.match(r'^1[3-9]\d{9}$', account):  # 手机号登录
            user = User.objects.get(mobile=account)
        else:  # 用户名登录
            user = User.objects.get(username=account)
    except User.DoesNotExist:  # 用户不存在
        return None

    # 返回结果
    return user


# class UsernameMobileBackend(ModelBackend):
#     """自定义用户登录"""
#     def authenticate(self, request, username=None, password=None, **kwargs):
#         """
#         重写认证方法
#         :param request:
#         :param username: 用户名或者手机号
#         :param password: 密码
#         :param kwargs:
#         :return:
#         """
#         # 获取用户对象
#         user = get_user(username)
#
#         # 检验密码
#         if user and user.check_password(password):
#             return user
